package com.program.facesigninsystem.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SignInCourseTypeHandler extends BaseTypeHandler<List<Integer>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
        // 将 List<Integer> 转换为逗号分隔的字符串并设置到 PreparedStatement 中
        if (parameter != null && !parameter.isEmpty()) {
            ps.setString(i, String.join(",", parameter.toString()));
        } else {
            ps.setString(i, "");
        }
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 获取列值并将逗号分隔的字符串转换为 List<Integer>
        String result = rs.getString(columnName);
        return convertStringToList(result);
    }

    @Override
    public List<Integer> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 获取列值并将逗号分隔的字符串转换为 List<Integer>
        String result = rs.getString(columnIndex);
        return convertStringToList(result);
    }

    @Override
    public List<Integer> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 获取列值并将逗号分隔的字符串转换为 List<Integer>
        String result = cs.getString(columnIndex);
        return convertStringToList(result);
    }

    private List<Integer> convertStringToList(String str) {
        List<Integer> resultList = new ArrayList<>();
        if (str != null && !str.isEmpty()) {
            String[] parts = str.split(",");
            for (String part : parts) {
                try {
                    resultList.add(Integer.parseInt(part.trim()));
                } catch (NumberFormatException e) {
                    // 如果解析失败，跳过该项
                }
            }
        }
        return resultList;
    }
}
